import React, { useEffect , useState} from 'react';
import sdk from 'qcloud-iotexplorer-h5-panel-sdk';
import { IMGURL,APIURL } from '../utils/common';
import { useHistory } from 'react-router-dom'
import { Toast} from 'antd-mobile';
import { Bzbgcolor } from './Jkcard';
import { Accordion } from 'antd-mobile';
import { bodyInfoObj } from '../utils/bodyinfo.js' //引入

import { ProgBar } from './ProgBar';
import moment from 'moment';
import PubSub from 'pubsub-js' //引入
// 当前时间
const current_time = (new Date()).valueOf()
let myuserInfo = sdk.userInfo
const c_type = 1
export function SjfxPage(props) {
	const history = useHistory()
	const Uid = history.location.state || {}
	const [bodyInfo, setbodyInfo] = useState();
	useEffect(() => {
		//插入数据
		getLastUserData()
		getThirdUserDataBYId(Uid)
		PubSub.subscribe('JkcardUdata',(msg, JkcardUdata) => {
			setbodyInfo(JkcardUdata)
			PubSub.unsubscribe("JkcardUdata");
		})
	}, [])
	function Accordionhead(props){
		const item = props.hitem
		return (
			<div className="aheadtit">
				<div className="fl-rsbc">
					<div className="ilimg fl-rc">
						{/* <img src={IMGURL+"clls_ic_time@2x.png"}/> */}
						{/* <div className="ilimg-bg fl-cc mgr5"></div> */}
						<span className="tittext">{item.name}</span>
					</div>
					<div className="r-img fl-rc mgr5">
						<span className="wcolor tittext mgr">{item.num}{item.unit}</span>
						<Bzbgcolor levelList={item.levelStand} levelNum={item.num} levelRange={item.levelRange}/>
					</div>
				</div>
			</div>
		)
	}
	const onChange = (key) => {
		console.log(key);
	}
	return(
		<div className="SjfxPage pagebg ">
			<div className="navtit bdwhite">数据分析</div>
			<Headinfo option_time={bodyInfo!=undefined ? bodyInfo.option_time : 0}/>
			<div className="bdwhite">
			{/* <div className="textcolor mgb fl-rsbc pd">
				<div className="tittext">需要关注的数据({badInfo.length}))</div>
				<div className="tittext">健康数据({goodInfo.length}))</div>
			</div> */}
			{
				bodyInfoObj.map((item,index)=>{
					return (
						<div className="lfachead" key={index}>
							<Accordion accordion openAnimation={{}} className="my-accordion" defaultActiveKey={item.name} onChange={onChange}>
								<Accordion.Panel header={<Accordionhead hitem={item}/>} key={item.name}>
								<div className="pd">
									{
									item.levelStand.length <= 2 &&
										<ProgBar levelRange ={item.levelRange} levelStand ={item.levelStand}/>
									}
									<div className="sgcolor tipstext">{item.definition}</div>
									<div className="sgcolor tipstext">{item.tips}</div>
								</div>
								</Accordion.Panel>
							</Accordion>
						</div>
					)
					}
				)
			}
			</div>
		</div>
	)
}
function Headinfo({option_time}){
	return(
		<div className="headinfo fl-cc">
			<div className="bigheadimg mgb"><img src={myuserInfo.Avatar == "" ? IMGURL+"headimg.png" : myuserInfo.Avatar}/></div>
			<div className="mgb numtext textcolor">{myuserInfo.NickName}</div>
			<div className="tsize wcolor">{moment(parseInt(option_time)).format("MM月DD日 HH:mm")} 测量</div>
		</div>
	)
}
// 根据生日算年龄
const matAge=(bir,c_time)=>{
	var age = Math.ceil((c_time-bir)/31536000000);
	return age
}
// 获取最新的用户基本信息
const getLastUserData =() =>{
	var request = require('superAgent')
	request
	.post(APIURL+'getlastuserinfo_tx')
	.send({
	  "productId":sdk.productId,
	  "deviceName":sdk.deviceName,
	  "wx_unionid":myuserInfo.UserID,
	  "username":myuserInfo.NickName,
	  "userimg":myuserInfo.Avatar,
	})
	// .set('Content-Type', 'application/text')
	.end(function(err, res){
	  if(res.body.code == 1){
		var JkcardUdata = res.body.data.third_user
		console.log('获取最新的用户数据',JkcardUdata)
		PubSub.publish('third_user',JkcardUdata)
	  }else{
		console.log('服务器'+res)
	  }
	})
}
// 实时计算出体脂数据
function getbdinfo(userinfo, hexString) {
  console.log("最后一次数据-userinfo")
  console.log(userinfo)
  var age = matAge(parseInt(userinfo.birthday), parseInt(current_time))
  var request = require('superAgent')
  request
    .post("https://lx.yodatech.cn/app/user/body/params")
    .send({
      "age": age,
      "appid": APPID,
      "height": parseFloat(userinfo.height),
      "hexString": hexString,
      "nonce": randomNum(1, 2048).toString(),
      "scaleType": 1,//体脂秤类型 1：四极秤 2：八极秤, 默认：1 四极秤
      "sex": parseInt(userinfo.sex),
      "signature": signature(),
      "timeStamp": new Date().valueOf()
      // "timeStamp": 1648804109989
    })
    .end(function (err, res) {
      console.log("最后一次数据")
      console.log(res)
      if (res.statusCode == 200) {
        var result = res.body
        console.log(result)
        if (result.code == 1000) {
          let bdinfo = result.data
          console.log("传入最后一次数据，实时从乐福计算出体脂数据")
          console.log(bdinfo)
          if (bdinfo != null) {
            PubSub.publish('xhData', bdinfo)
          }
          else {
            Toast.fail("获取信息失败，请确保您已录入体重、身高、年龄！")
          }
        }
      }
      else {
        console.log('服务器出错' + res)
      }
    })
}
// 传入最后一次数据，实时从乐福计算出体脂数据
function getlastbdinfo(userinfo,impedance,weightKg){
	// return new Promise(function (resolve, reject) {
		var age = matAge(parseInt(userinfo.birthday),parseInt(current_time))
		var request = require('superAgent')
		console.log(userinfo)
		request
		.post("https://iotapi.sziton.com/api/ex_inter_face_info/getBodyInfo")
		.send({
			"age":age,
			"height":userinfo.height,
			"sex":userinfo.sex,
			"impedance":impedance,
			"weightKg":weightKg,
			"c_type":c_type
		})
		.end(function(err, res){
			if(res.body.code == 1){
				let bdinfo = res.body.data.data.obj
				// resolve(bdinfo);
				PubSub.publish('bdinfo',bdinfo)
			}
			else{
				Toast.fail("获取信息失败，请确保您已录入体重、身高、年龄！")
				// reject(new Error(res.body));
			}
		})
	// });
  }
//   通过ID查询体脂数据
const getThirdUserDataBYId =(Uid) =>{
	var request = require('superAgent')
	request
	.post(APIURL+'getThirdUserDataBYId')
	.send({"id":Uid})
	.end(function(err, res){
		var JkcardUdata
		if(res.body.code == 1){
		JkcardUdata = res.body.data.data
		console.log('JkcardUdata',JkcardUdata)
		PubSub.publish('JkcardUdata',JkcardUdata)
		}else{
		console.log('服务器'+res)
		}
	})
}